<script setup lang="ts">
import { watch, ref, markRaw, onMounted } from "vue";
import leftCompWrapper from "../common/leftCompWrapper.vue";
import * as echarts from "echarts";

defineOptions({
  name: "VChartLine"
});
const echartRef = ref();
let echartInstance: echarts.ECharts;
const isCollapsed = ref(false);
const props = withDefaults(
  defineProps<{
    propValue?: {
      contentList: Array<any>;
      title?: string;
      collapsed?: boolean;
      iconName?: string;
      option?: Record<string, any>;
    };
    element?: {
      style: {
        width?: number;
        height?: number;
        display?: string;
      };
    };
  }>(),
  {
    propValue: () => ({
      contentList: [],
      option: {},
      title: "",
      collapsed: false,
      iconName: "alert"
    }),
    element: () => ({ style: {} })
  }
);
onMounted(() => {
  echartInstance = markRaw(
    echarts.init(echartRef.value, undefined, {
      width: props.element!.style!.width! - 47,
      height: props.element.style.height! - 63
    })
  );
  renderChart(props.propValue.contentList as any);
});
function renderChart(newVal = []) {
  try {
    let option = deepCopy(props.propValue.option);
    option.series[0].name = option.legend.data[0];
    option.series[1].name = option.legend.data[1];
    // 更新大小
    if (echartInstance && echartInstance.resize) {
      echartInstance.resize({
        width: props.element!.style!.width! - 47,
        height: props.element.style.height! - 63
      });

      // 配置参数
      echartInstance.setOption(option);
    }
  } catch (e) {
    console.error(e);
  }
}

//用于编辑器参数改变时响应变化
watch(
  () => props.element,
  newVal => {
    // console.log(newVal);
    renderChart(props.propValue.contentList);
  },
  { deep: true, immediate: true }
);
watch(
  () => props.propValue.option,
  newVal => {
    renderChart(newVal as any);
  },
  { deep: true, immediate: true }
);
function deepCopy(data) {
  try {
    return JSON.parse(JSON.stringify(data));
  } catch (error) {
    console.error(error);
    return {};
  }
}
</script>

<template>
  <leftCompWrapper v-model="isCollapsed" :title="propValue.title" :icon-name="propValue.iconName" :has-collapsed="propValue.collapsed">
    <div ref="echartRef" />
  </leftCompWrapper>
</template>
